<template>
    <div :style="{ padding: '15px' }">
        <!-- 右侧部分 -->
        <el-collapse accordion v-for="(v, k) in getuserquestion" :key="`${k}_3`" class="border-0 question-collapse">
            <el-row class="border-bottom">
                <div class="txt col pl-0 pr-0">
                    <div class="float-start">
                        <strong :class="ALLTYPE[v.resultdata] ? ALLTYPE[v.resultdata][1] : ALLTYPE['WT'][1]">
                            {{ v.resultdata ? ALLTYPE[v.resultdata] ? ALLTYPE[v.resultdata][1] : ALLTYPE['WT'][1] : ""
                            }}
                        </strong>
                    </div>
                    <div class="float-right tjsj text-right">
                        <span>提交时间：{{ v.createdAt ? TimeYH(v.createdAt) : "-" }}</span>
                        <span>编程语言：{{ getLanguage(v) }}
                        </span>
                    </div>
                    <span class="clearfix"></span>
                </div>
            </el-row>
            <!-- <div v-if="Array.isArray(v.info)"> -->
            <el-row class="mt-2 mb-2 submission-title margin-bottom20">
                <h5 class="margin-bottom0">测试点信息</h5>
                <div v-if="k === 0" :style="{ width: '150px', textAlign: 'right' }">
                    <el-button class="submission-btn" size="default" type="primary" v-if="length < 30"
                        @click="centerDialogVisible = true">
                        贡献测试点
                    </el-button>
                </div>
            </el-row>
            <div v-if="Array.isArray(v.info)" class="row" v-for="(info1, infok) in subtask(v.info)" :key="'a_' + infok">
                <div class="col-12">Subtask {{ infok + 1 }}</div>
                <div class="col-12">
                    <div class="classtz border text-center" v-for="(e, k) in info1" :key="`b_${k}`"
                        :class="e.tn ? e.tn[1] : ALLTYPE['RE'][1]" @mouseleave="mouseleave" @mouseenter="mouseenter">
                        <div class="div-1-1">
                            <div class="text-left">#{{ k + 1 }}</div>
                            <strong class="text-uppercase" v-text="e.tn ? e.tn[0] : 'RE'"></strong>
                            <br />
                            <span>{{ time(v.result, [e]) }}/{{ memory(v.result, e) }}</span>
                        </div>
                        <el-collapse-transition>
                            <div @click="downloadtestcase(e.ID, k)" class="transition">
                                <div>下载测试点</div>
                            </div>
                        </el-collapse-transition>
                    </div>
                </div>
            </div>
            <!-- </div> -->
            <el-row v-else>
                <div class="col p-0 mb-4 mt-4">
                    <h5>错误提示</h5>
                    <pre class="m-0 code-pre" v-text="v.info?.msg"></pre>
                </div>
            </el-row>
            <el-row class="submission-title margin-bottom20">
                <h5 class="margin-bottom0">源代码</h5>
                <div>
                    <el-button class="submission-btn" size="default" type="primary" @click="toMyEditor(v.context)">编辑器打开
                    </el-button>
                    <el-button class="submission-btn" size="default" type="primary" @click="myCopy(v.context)">复制源代码
                    </el-button>
                </div>
            </el-row>
            <div class="col p-0">
                <pre v-highlight :class="'language-' + v.language">
          <code v-text="v.context" class="code-pre"/>
        </pre>
            </div>
        </el-collapse>
        <el-dialog v-model="centerDialogVisible" class="my_el-dialog__body" title="添加测试点" width="950px">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    添加测试点
                </span>
            </template>
            <div class="testcase">
                <div class="row">
                    <div class="col">
                        感谢您为这道题贡献测试点！~\(≥▽≤)/~
                        <br>
                        为了保证题解质量，您提交的测试点我们会在第一时间进行审核，通过后会作为后续评测的标准测试点展示。
                    </div>
                    <div class="col-2 text-right">
                        <el-popover placement="left-start" :width="400" trigger="click">
                            <template #reference>
                                <el-button class="disbutton">
                                    审核规则 &nbsp;
                                    <el-icon :size="16">
                                        <QuestionFilled />
                                    </el-icon>
                                </el-button>
                            </template>
                            <div>
                                <div>审核将按照以下规则：</div>
                                <div>1）测试点正确：测试点需要完全符合题目要求、确保正确；</div>
                                <div>2）测试点无重复：当前已有测试点中，没有完全重复或基本重复的测试点。</div>
                                <!-- <div>如对测试点有疑问，可以添加网站右上角助教老师沟通。</div> -->
                                <br>
                                <!-- <div>每贡献一个测试点并审核通过，+1贡献积分，+1金币。</div>
                <div>贡献积分会持续累加，不会消耗。</div> -->
                            </div>
                        </el-popover>
                    </div>
                </div>
                <el-row>
                </el-row>
                <div class="h33">
                </div>
                <el-row class="ex">
                    <el-col :span="24" class="text-right">
                        <el-popover placement="bottom" :width="400" trigger="click">
                            <template #reference>
                                <el-button size="default" text :style="{ marginRight: '12px' }">
                                    上传说明
                                    <el-icon :size="16">
                                        <QuestionFilled />
                                    </el-icon>
                                </el-button>
                            </template>
                            <div>
                                <div>文件形式上传测试点要求：</div>
                                <div>1）测试点文件打包成zip文件；</div>
                                <div>2）每一个测试点文件需要相同名称的两个文件,输入文件为.in，输出文件为.out或者.ans；</div>
                                <div>3）目前支持输入输出单个文件最大为50M，后续会对部分题目开放更大空间。</div>
                            </div>
                        </el-popover>
                        <el-upload :disabled="length > 30" action="/" :show-file-list="false" accept=".zip"
                            :http-request="request" class="d-inline-block">
                            <el-button size="default" type="primary" :disabled="length > 30">上传测试点</el-button>
                        </el-upload>
                    </el-col>
                </el-row>
                <el-form ref="form" class="container-xl form-xl" :model="formrule" label-width="120px">
                    <div class="row">
                        <div class="col">输入</div>
                        <div class="col">输出</div>
                        <div :style="{ width: '48px' }">
                            <el-icon class="el-icon-1" @click="usertest.push({ input: '', output: '' })">
                                <Plus />
                            </el-icon>
                        </div>
                    </div>
                    <div class="row" :style="{ marginTop: '12px' }" v-for="(n, m) in usertest" :key="'1_' + m">
                        <div class="col">
                            <el-input :type="n.type ? 'text' : 'textarea'" v-model="n.input" :rows="5"
                                :disabled="n.type == 'url'" placeholder="测试点输入"></el-input>
                        </div>
                        <div class="col">
                            <el-input :type="n.type ? 'text' : 'textarea'" v-model="n.output" :rows="5"
                                :disabled="n.type == 'url'" placeholder="测试点输出"></el-input>
                        </div>
                        <div :style="{ width: '48px' }">
                            <el-icon class="el-icon-2" @click="usertest.splice(m, 1)">
                                <Minus />
                            </el-icon>
                        </div>
                    </div>
                    <div class="m-mt-6 m-mb-3">备注</div>
                    <div>
                        <el-input type="textarea" v-model="usercont" :rows="2"></el-input>
                    </div>
                </el-form>
                <el-row>
                    <el-col :span="12"></el-col>
                    <el-col :span="12" class="text-right">
                        <el-button size="default" type="primary" @click="submit" v-show="length < 30"
                            :disabled="length > 30">提交审核
                        </el-button>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { Minus, Plus, QuestionFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { computed, h, onMounted, reactive, ref, watch } from "vue";
import { useStore } from "vuex";
import { asynccreatequestiontestcasesuser, asyncselectuserquestion } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { ALLTYPE } from "@/util/jianchatime";
import subtask from "../../../util/subtask";
import { TimeYH } from "../../../util/time";

import { useClipboard } from '@vueuse/core';
import type { Action } from "element-plus/lib/components";
// import highlight from "highlight.js";
import { useRoute } from "vue-router";
import { downloadtext } from "../../../util/dowmload";
import { updatezip } from "../../../util/updateoss";
const { text, copy, copied, isSupported } = useClipboard()
type P = {
    isSub: boolean;
    user: Studycodemodel.Iuser;
    ID?: number;
    question: Studycodemodel.Iquestion
    submissionRow: Studycodemodel.Iuserquestion
};
interface Iusertest extends Studycodemodel.Iquestiontestcasesuser { }
const prop = defineProps<P>()
const emit = defineEmits<{
    (e: 'update:showCaseDetail', value: boolean): void,
    (e: 'update:editerContent', value: string): void,
}>()

const usertest = ref<Iusertest[]>([{ input: "", output: "" }]);

const length = computed(() => {
    return prop.question.testcases?.length || 0
})

const route = useRoute()
const range = computed(() => {
    return route.query.range
})

const formrule = reactive({});
const usercont = ref("");
const centerDialogVisible = ref(false)
const userquestion = ref<Studycodemodel.Iuserquestion[]>([{}])
const offset = ref(0)
const count = ref(0)
const store = useStore(Storekey)
const user = computed(() => {
    return store.state.user
})

watch(() => prop.isSub, (v) => {
    if (v) {
        start()
    }
})
watch(() => offset.value, (v) => {
    start()
})

onMounted(() => {
    userquestion.value = [prop.submissionRow]
})

watch(() => prop.ID, () => {
    start()
})
watch(() => prop.submissionRow, (v) => {
    userquestion.value = [v || {}]
    // highlightCode()
})

function getLanguage(row: Studycodemodel.Iuserquestion): string {
    let rowLanguage = row.language?.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
    rowLanguage = rowLanguage !== 'Cpp' ? rowLanguage : 'C++'
    return rowLanguage || "-"
}

const getuserquestion = computed(() => {
    return userquestion.value
})

function time(esult: Studycodemodel.Iuserquestion["result"],
    info: Studycodemodel.Iuserquestion["info"]) {
    if (!Array.isArray(info)) return NaN;
    let t = 0;
    for (let v of info) {
        if (t < Number(v.t)) {
            t = Number(v.t);
        }
    }
    return Math.floor(t) + "ms";
}

function memory(esult: Studycodemodel.Iuserquestion["result"],
    info: Studycodemodel.Iuserquestioninfo) {
    if (typeof info.memory === "number") {
        return info.memory / 1024 < 1
            ? Math.floor(info.memory) + "kb"
            : Math.floor(info.memory / 1024) + "mb";
    } else if (typeof info.memory === "object") {
        return "4kb";
    }
    return info.memory || "4kb";
}

// 获取指定qid、uid的提交list
async function start() {
    // return
    if (user.value && prop.ID) {
        const data = await asyncselectuserquestion({
            _offset: offset.value,
            userid: user.value.ID,
            _limit: 10,
            questionid: prop.ID,
            _order: 'ID',
            _sortable: 'DESC'
        });
        userquestion.value = [data.rows[0] || {}] // 默认显示第一次提交的测试用例详情
        count.value = data.count;
    }
    // highlightCode()
}

// function highlightCode() {
//   nextTick(() => {
//     // 有无提交
//     if (Object.keys(userquestion.value[0]).length) {
//       highlight.highlightAll()
//     }
//   })
// }

defineExpose({
    start,
    count
})

function downloadtestcase(ID?: number, index?: number) {
    fetch(`/api/download/downloadtestcase?ID=${ID}`).then(e => e.json()).then((e: { error: number, msg: string, data: Studycodemodel.Itestcases }) => {
        if (e.error) {
            ElMessage.error(e.msg)
            return
        }
        const data: { name: string, text: string }[] = [

        ]
        if (e.data.input) {
            data.push({
                name: `${index}.in`,
                text: e.data.input
            })
        }
        if (e.data.output) {
            data.push({
                name: `${index}.out`,
                text: e.data.output
            })
        }
        if (e.data) {
            downloadtext(e.data.type, prop.ID + '_' + index, data)
        } else {
            ElMessage.error('文件找不到')
        }
    })
}
function mouseleave(e: MouseEvent) {
    if (range.value === 'codeforces') return
    if (e.target) {
        const n: any = e.target
        n.querySelector('.div-1-1').style.display = 'block'
        const div: HTMLDivElement = n.querySelector('.transition')

        const bgcolor = Object.values(ALLTYPE).map(e => e[1]).find(t => {
            return n.className.includes(t)
        })
        div.style.display = 'none'
        div.className = `transition bg-${n.className}`
        div.style.height = '0'
    }
}

function mouseenter(e: MouseEvent) {
    if (range.value === 'codeforces') return

    if (e.target) {
        const n: any = e.target
        n.querySelector('.div-1-1').style.display = 'none'
        const div: HTMLDivElement = n.querySelector('.transition')
        const bgcolor = Object.values(ALLTYPE).map(e => e[1]).find(t => {
            return n.className.includes(t)
        })
        div.style.display = 'flex'
        div.className = `transition bg-${bgcolor}`
        div.style.height = '100%'
    }
}

function submit() {
    const data: Studycodemodel.Iquestiontestcasesuser[] = [];
    usertest.value.forEach((e) => {
        const { ...t } = e;
        if (e.input && e.output) {
            t.context = usercont.value;
            t.questionid = prop.ID;
            t.userid = user.value?.ID;
            data.push(t);
        }
    });
    if (data.length) {
        asynccreatequestiontestcasesuser({ questiontestcasesuser: data })
            .then((n) => {
                usertest.value = [{ input: "", output: "" }]
                ElMessage.success("提交成功");
                ElMessageBox({
                    title: '提交成功',
                    message: h('p', null, [
                        h('img', { src: 'https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/image/Banner_1', width: '488' }),
                        h('span', null, '我们会在24小时内审核完成，通过后会进行公开展示并增加您的贡献积分。'),
                        h('br', null, ''),
                        h('br', {}, ''),
                        h('span', {}, '贡献将按照以下规则：'),
                        h('br', {}, ''),
                        h('span', {}, '1）测试点正确：测试点需要完全符合题目要求、确保正确；'),
                        h('br', {}, ''),
                        h('span', {}, '2）测试点无重复：当前已有测试点中，没有完全重复或基本重复的测试点。'),
                        h('br', {}, ''),
                        h('br', {}, ''),
                        h('span', {}, '如对测试点有疑问，可以添加网站右上角助教老师沟通。'),
                    ]),
                    customStyle: {
                        'width': '520px'
                    },
                    confirmButtonText: '好的',
                    callback: (action: Action) => {
                        centerDialogVisible.value = false
                    },
                    buttonSize: 'default'
                })
            })
            .catch((n) => {
                ElMessage.error(n);
            });
    } else {
        ElMessage.success("请填写测试点");
    }
}

async function request(file: { file: File }, c: Function) {
    const { size } = file.file;
    if (size > 1024 * 1024 * 50) {
        ElMessage.error("上传文件过大，最大只能上传50MB");
        return;
    }
    ElNotification({
        title: "解压",
        message: "开始解压",
        type: "info",
    });

    const data = await updatezip(file.file);
    data.forEach((e) => {
        const { input, output } = e;
        usertest.value.push({
            input,
            output,
            userid: user.value?.ID,
            questionid: prop.ID,
            type: "url",
        });
    });
    ElNotification({
        title: "解压",
        message: "解压成功",
        type: "success",
    });
    c("a.zip");
}

function myCopy(str: string) {
    try {
        str ? copy(str) : '';
        ElMessage.success("复制成功");
    } catch (error) {
        console.log("myCopy error=>", str, error)
    }
}

function toMyEditor(v) {
    // 显示编辑器
    emit('update:showCaseDetail', false)
    // 代码传递
    emit('update:editerContent', v)
}
</script>

<style scoped>
.submission-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 按钮 */
.submission-btn {
    /* width: 100px; */
    /* height: 36px; */
    border-radius: 4px;
    background-color: rgba(70, 131, 250, 1);
    font-size: 14px;
}

/* ===================old======================= */
.table pre {
    margin-bottom: 0px;
}

h5 {
    font-size: 16px;
}

.txt {
    padding-bottom: 12px;
}

.txt strong {
    line-height: 24px;
    padding-right: 10px;
    font-size: 24px;
    display: inline-block;
}

.div-hr {
    height: 41px;
    padding-top: 20px;
    padding-bottom: 20px;
}

.div-hr div {
    height: 1px;
    background-color: cornsilk;
}

.question-collapse {
    padding: 20px 0;
}

.question-collapse img {
    line-height: 40px;
}

.tjsj {
    line-height: 24px;
    text-align: end;
}

.tjsj span {
    display: inline-block;
    padding-right: 10px;
    color: var(--color-606266);
}

.text-hide {
    padding-left: 10px;
    padding-top: 6px;
}

.classtz {
    width: 100px;
    height: 100px;
    display: inline-block;
    margin: 5px 10px 5px 0;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
}

.classtz .div-1-1 {
    border-top-width: 4px;
    border-top-style: solid;
}

.co9A97AD {
    color: #9a97ad;
}

.div-1-1 .text-left {
    font-size: 14px;
    /* margin-top: 10px; */
    padding-left: 12px;
    color: #909399 !important;
}

.div-1-1 .text-uppercase {
    font-size: 28px;
    display: inline-block;
    /* margin-bottom: 10px; */
}

.transition {
    transition: 1s all ease;
    display: none;
    color: #fff;
    text-align: center;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
}

.div-1-1 span {
    font-size: 14px;
    font-weight: 400;
    line-height: 16px;
    color: #c0c4cc;
}

.context1 {
    border: 1px solid #d9d9d9;
}

.list-group-item {
    border-left: none;
    border-top: none;
    border-bottom: none;
    border-right: 1px solid #d9d9d9;
    cursor: pointer;
    background-color: #f5f5f5;
}

.list-group-item:hover {
    background-color: #fff;
}

.list-group-horizontal {
    width: 100%;
    border-left: 1px solid #d9d9d9;
    border-top: 1px solid #d9d9d9;
    border-bottom: none;
    border-right: 1px solid #d9d9d9;
    border-bottom-left-radius: inherit;
    border-bottom-right-radius: inherit;
    overflow-x: auto;
}

.testcase .pre {
    border-color: #d9d9d9;
    border: 1px solid #d9d9d9;
    padding: 12px;

    box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
        0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
    border-bottom-left-radius: 2px;
    border-bottom-right-radius: 2px;
}

.testcase pre {
    border: none;
    background-color: #f5f5f5;
}

.h33 {
    font-size: 18px;
    color: var(--color-43);
    margin-top: 24px;
    margin-bottom: 12px;
}

.ex {
    margin-bottom: 12px;
}

.ex1 {
    font-size: 12px;
    color: #8c8c8c;
}

.form-xl {
    border: 1px solid #d9d9d9;
    /* Depth 4 */

    box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
        0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
    border-radius: 2px;
    padding-top: 12px;
    padding-bottom: 12px;
    margin-bottom: 12px;
}

.el-form .row {
    --bs-gutter-x: 24px;
}

.el-icon-1 {
    width: 24px;
    height: 24px;
    background-color: var(--color-cheng);
    line-height: 24px;
    color: #fff;
    border-radius: 2px;
    text-align: center;
    cursor: pointer;
}

.el-icon-2 {
    width: 24px;
    height: 24px;
    background-color: #d9d9d9;
    line-height: 24px;
    color: #fff;
    border-radius: 2px;
    text-align: center;
    cursor: pointer;
}

.disbutton {
    border: none;
    background-color: #f5f5f5;
    --el-button-hover-color: "#000";
    --el-button-hover-background-color: #f5f5f5;
    height: 28px;
    line-height: 28px;
    padding-top: 0;
    padding-bottom: 0;
    padding-left: 12px;
    padding-right: 12px;
}
</style>

<style>
.question-collapse .is-active {
    background-color: var(--color-d2e4ff) !important;
    border-bottom-width: 0;
}

.question-collapse .el-collapse-item__content {
    padding-bottom: 0 !important;
}
</style>